import React, { useEffect, useState } from "react";
import './styles/main.css'
import './styles/iconfont.css'
import './styles/font.woff2'
import axios from "axios";
import { v4 as uuidv4 } from 'uuid';

interface Todo {
  id: string;
  text: string;
  completed: boolean;
  ctime: number;
  mtime: number
}

const App: React.FC = () => {
  const [todos, setTodos] = useState<Todo[]>([]);
  const [inputValue, setInputValue] = useState("");

  function getTodas(): void {
    axios.get('/api/todos').then((res) => {
      const data = res.data
      const histTodos: Todo[] = []
      console.log(data[0].ctime);
      for (let index = 0; index < data.length; index++) { 
        const todo: Todo = {
          id: data[index].id,
          text: data[index].text,
          completed: Boolean(data[index].completed),
          ctime: data[index].ctime,
          mtime: data[index].mtime
        }
        histTodos.push(todo)
      }
      setTodos(histTodos)
    })
  }

  const AddTodo = (e) => {
    if (!inputValue.trim()) return;
    const currentTime = new Date().getTime();
    if (e.key === 'Enter') {
      const newTodo: Todo = {
        id: uuidv4(),
        text: inputValue,
        completed: false,
        ctime: currentTime,
        mtime: currentTime
      };
      axios.post('/api/todos',
        newTodo
      ).then((res) => {
        console.log(res);
        console.log("添加成功");
      })
      setTodos([...todos, newTodo]);
      setInputValue("");
    }
  };


  const FinshTodo = (e: React.MouseEvent<HTMLElement, MouseEvent>, id: string) => {
    const parent = e.currentTarget.parentElement;
    const todoMap = new Map(todos.map(todo => [todo.id, todo]))
    const todo = todoMap.get(id)
    const completed = todo.completed
    if (completed) { parent.className = 'todo-item todo-finished' } else { parent.className = 'todo-item' }
    setTodos((prevTodos) =>
      prevTodos.map((todo) =>
        todo.id === id ? { ...todo, completed: !todo.completed } : todo
      )
    )
    const currentTime = new Date().getTime();
    const newtodo = { ...todo, completed: !completed, mtime: currentTime }
    axios.put(`/api/todos/${id}`, newtodo).then((res) => {
      console.log("修改成功");
    })
    axios.patch(`/api/todos/${id}`, newtodo).then((res) => {
      console.log("修改成功");
    })
  };

  const handleRemoveTodo = (id: string) => {
    axios.delete(`/api/todos/${id}`).then((res) => {
      console.log(res);
      console.log("删除成功");
    })
    setTodos((prevTodos) => prevTodos.filter((todo) => todo.id !== id));
  };

  function formatDateTime(ms: number): string {
    const date = new Date(ms);
    const year = date.getFullYear();
    const month = padZero(date.getMonth() + 1);
    const day = padZero(date.getDate());
    const hour = padZero(date.getHours());
    const minute = padZero(date.getMinutes());
    const second = padZero(date.getSeconds());
    return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
  }

  function padZero(num: number): string {
    return num < 10 ? `0${num}` : `${num}`;
  }


  useEffect(() => {
    console.log(
      `%cWelcome to my website!`,
      `
        color: white;
        font-size: 50px;
        text-shadow:
          3px 3px 0 #f44336,
          -1px -1px 0 #2196F3,
          1px -1px 0 #2196F3,
          -1px 1px 0 #2196F3,
          1px 1px 0 #2196F3;
      `
    );

    console.log(
      `%c在这里你可以看到类似于掘金的主页 
    --by xiaowen`,
      `
        font-size: 25px;
        color: #2196F3;
      `
    );
    getTodas()
  }, [])

  return (
    <div id="App" className="App">
      <header>
        <div className="title">Todo List</div>
        <input
          id="input"
          className="input"
          type="text"
          placeholder="What needs to be done?"
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
          onKeyDown={(e) => AddTodo(e)}
        />
      </header>

      <section>
        {todos.map((todo) => (
          <div key={todo.id} className={todo.completed === false ? "todo-item" : "todo-item todo-finished"}>
            <i className="iconfont icon-checkbox"
              onClick={(e) => FinshTodo(e, todo.id)}
            >
            </i>
            <span className="todo-title">
              {todo.text}
            </span>
            <span className="add-time">{formatDateTime(todo.ctime)}</span>
            <i className="iconfont icon-delete" onClick={() => handleRemoveTodo(todo.id)}></i>
          </div>
        ))}
      </section>
    </div>
  );
};

export default App;
